﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Diary.Win
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        //测试数据
        //List<Model.Category> categories = new List<Model.Category>();

        private void tsmiCategoryCreate_Click(object sender, EventArgs e)
        {
            TreeNode tn_select = tvCategory.SelectedNode;

            CategoryManagerForm form = new CategoryManagerForm();
            if (tn_select != null)
            {
                Model.Category select_model = tn_select.Tag as Model.Category;
                if (select_model != null)
                {
                    form.CategoryData.ParentId = select_model.Id;
                }
            }
            
            if (form.ShowDialog() != DialogResult.OK) return;

            Model.Category model = Diary.BAL.Category.Insert(form.CategoryData);
            if (model == null)
            {
                //新增失败
                return;
            }

            TreeNode tn = new TreeNode()
            {
                Text = model.Name,
                Tag = model,
            };
            if (tn_select == null)
            {
                tvCategory.Nodes.Add(tn);
            }
            else
            {
                tn_select.Nodes.Add(tn);
                tn_select.Expand();
            }
        }

        TreeNode find_by_id(TreeNode tnParent, int findId)
        {
            TreeNodeCollection tnc = (tnParent == null) ? tvCategory.Nodes : tnParent.Nodes;

            foreach (TreeNode node in tnc)
            {
                Model.Category model = node.Tag as Model.Category;
                if (model.Id == findId) return node;

                if (node.Nodes.Count > 0)
                {
                    TreeNode tn = find_by_id(node, findId);
                    if (tn != null) return tn;
                }
            }
            return null;
        }

        Model.Category get_select_category()
        {
            if (tvCategory.SelectedNode == null) return null;
            if (tvCategory.SelectedNode.Tag == null) return null;
            return tvCategory.SelectedNode.Tag as Model.Category;
        }


        private void tsmiCategoryModify_Click(object sender, EventArgs e)
        {
            TreeNode tn_select = tvCategory.SelectedNode;
            if (tn_select == null) return;

            TreeNode oldParentNode = tn_select.Parent;

            Model.Category model = tn_select.Tag as Model.Category;
            if (model == null) return;

            CategoryManagerForm form = new CategoryManagerForm();
            form.CategoryData = model;
            if (form.ShowDialog() != DialogResult.OK) return;

            if (!BAL.Category.Modify(model))
            {
                //修改失败
                return;
            }

            tn_select.Text = model.Name;

            TreeNode newParentNode = find_by_id(null, model.ParentId);

            if (oldParentNode != newParentNode)
            {
                //删除原节点
                if (oldParentNode != null)
                {
                    oldParentNode.Nodes.Remove(tn_select);
                }
                else
                {
                    tvCategory.Nodes.Remove(tn_select);
                }

                //添加新节点
                if (newParentNode != null)
                {
                    newParentNode.Nodes.Add(tn_select);
                }
                else
                {
                    tvCategory.Nodes.Add(tn_select);
                }
            }
        }

        private void tsmiCategoryDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除吗？", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Model.Category model = get_select_category();
                if (model != null)
                {
                    if (BAL.Category.Delete(model.Id))
                    {
                        tvCategory.SelectedNode.Remove();
                    }
                }
            }
        }

        private void cmsCategory_Opening(object sender, CancelEventArgs e)
        {
            bool hasSelected = (tvCategory.SelectedNode != null);
            tsmiCategoryModify.Enabled = hasSelected;
            tsmiCategoryDelete.Enabled = hasSelected;

            //以下代码为不显示修改或删除菜单项
            //tsmiCategoryModify.Visible = hasSelected;
            //tsmiCategoryDelete.Visible = hasSelected;
        }

        private void tvCategory_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Model.Category model = e.Node.Tag as Model.Category;
                if (model != null)
                {
                    search(model.Id);
                }
            }
        }

        void search(int? categoryId=null)
        {
            if (!categoryId.HasValue)
            {
                if (tvCategory.SelectedNode != null)
                {
                    Model.Category model = tvCategory.SelectedNode.Tag as Model.Category;
                    if (model != null)
                    {
                        categoryId = model.Id;
                    }
                }
            }
            _contents = BAL.Content.query(categoryId);
            dgvContent_reload();
        }


        private void tvCategory_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (tvCategory.SelectedNode != null)
                {
                    Point ptMouse = PointToClient(MousePosition);
                    if (!tvCategory.SelectedNode.Bounds.Contains(ptMouse))
                    {
                        tvCategory.SelectedNode = null;
                    }
                }
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            string[] filenames = { "folder.png", "key.png", "text.png" };
            foreach (string filename in filenames)
            {
                string path = string.Format("{0}\\Resource\\png\\{1}", Application.StartupPath, filename);
                imgsCategory.Images.Add(Image.FromFile(path));
            }

            List<Model.Category> categories = BAL.Category.query_all();
            categories.Add( new Model.Category() { Id = -1, Name = "全部" } );
            categories = Model.Category.Sort(categories);
            foreach (Model.Category category in categories)
            {
                TreeNode tn_parent = find_by_id(null, category.ParentId);
                TreeNodeCollection tnc = (tn_parent == null) ? tvCategory.Nodes : tn_parent.Nodes;
                TreeNode tn = tnc.Add(category.Name);
                tn.Tag = category;
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            TreeNode tn_select = tvCategory.SelectedNode;

            ContentManagerForm form = new ContentManagerForm();
            if (tn_select != null)
            {
                Model.Category select_model = tn_select.Tag as Model.Category;
                if (select_model != null)
                {
                    form.ContentData.CategoryId = select_model.Id;
                }
            }

            DialogResult dr = form.ShowDialog();
            tvCategory.Focus();

            if (dr != DialogResult.OK)
            {
                return;
            }

            Model.Content model = BAL.Content.Insert(form.ContentData);
            if (model == null)
            {
                //新增失败
                return;
            }
        }

        List<Model.Content> _contents = new List<Model.Content>();
        private void btnSearch_Click(object sender, EventArgs e)
        {
            _contents = BAL.Content.query_all();
            dgvContent_reload();
        }

        void dgvContent_reload()
        {
            dgvContent.RowCount = _contents.Count;
            dgvContent.Invalidate(false);
        }


        private void dgvContent_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            if (_contents.Count == 0) return;

            Model.Content model = _contents[e.RowIndex] as Model.Content;
            if (model == null) return;

            string v = "";
            switch (e.ColumnIndex)
            {
                case 0:
                    v = model.Title;
                    break;
                case 1:
                    {
                        v = model.RealTime.ToString("yyyy-MM-dd HH:mm");
                    }
                    break;
                case 2:
                    {
                        foreach (Model.Tag tag in model.Tags)
                        {
                            v += tag.Name + ",";
                        }
                        if (!string.IsNullOrEmpty(v)) v = v.Substring(0, v.Length - 1);
                    }
                    break;
                case 3:
                    {
                        v = model.Remark;
                    }
                    break;
                case 4:
                    v = "复制";
                    break;
                case 5:
                    v = "删除";
                    break;
            }
            e.Value = v;
        }

        private void dgvContent_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (_contents.Count == 0) return;
            if (e.RowIndex < 0) return;
            Model.Content model = _contents[e.RowIndex] as Model.Content;
            if (model == null) return;

            switch (e.ColumnIndex)
            {
                case 4:
                    model.Id = 0;
                    model.Title = model.Title + " (副本)";
                    model.CreateTime = DateTime.Now;
                    model.ModifyTime = DateTime.Now;
                    model.RealTime = DateTime.Now;
                    if (BAL.Content.Insert(model) != null)
                    {
                        search();
                    }
                    break;
                case 5:
                    if (MessageBox.Show("确定要删除吗？", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        if (BAL.Content.Delete(model.Id))
                        {
                            search();
                        }
                    }
                    break;
            }
        }

        private void tsmiSetting_Click(object sender, EventArgs e)
        {
            SettingForm form = new SettingForm();
            form.ShowDialog();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            bool isAutoBackupAtExit = BAL.Setting.get_bool_value("AutoBackupAtExit");
            if (isAutoBackupAtExit)
            {
                Global.Default.BackupDB();
            }
        }

        private void dgvContent_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

        }
        void EditContent(int rowIndex)
        {
            Model.Content model = _contents[rowIndex] as Model.Content;
            if (model == null) return;

            ContentManagerForm form = new ContentManagerForm();
            form.ContentData = model;
            form.Show();
        }

        private void dgvContent_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dgvContent.SelectedRows.Count <= 0) return;
            EditContent(dgvContent.SelectedRows[0].Index);
        }
    }
}
